package com.liuzy.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * 
 * @author liuzy
 * @since 2015年10月25日
 */
public class Util {
	public static boolean isHtml(String path) {
		return path.contains("<") || path.contains(">");
	}

	/**
	 * 读取地址网页HTML
	 */
	public static String read2html(String url) throws IOException {
		HttpURLConnection conn = null;
		InputStream is = null;
		GZIPInputStream gzin = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			URL uri = new URL(url);
			conn = (HttpURLConnection) uri.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			is = conn.getInputStream();
			if ("chunked".equals(conn.getHeaderField("Transfer-Encoding"))) {
				gzin = new GZIPInputStream(is);
				isr = new InputStreamReader(gzin, "gb2312");
				br = new BufferedReader(isr);
				StringBuffer sb = new StringBuffer();
				String temp;
				while ((temp = br.readLine()) != null) {
					sb.append(temp);
					sb.append("\n");
				}
				return sb.toString();
			} else {
				ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = -1;
				while ((len = is.read(buffer)) != -1) {
					outSteam.write(buffer, 0, len);
				}
				outSteam.close();
				is.close();
				byte[] bytes = outSteam.toByteArray();
				String charset = getCharset(bytes);
				if (charset != null) {
					return new String(bytes, charset);
				}
			}
		} finally {
			try {
				if (isr != null)
					isr.close();
				if (gzin != null)
					gzin.close();
				if (br != null)
					br.close();
				if (is != null)
					is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 识别网页面内容编码
	 */
	private static String getCharset(byte[] bytes) {
		String temp;
		if (bytes.length < 512) {
			temp = new String(bytes);
		} else {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < 512; i++) {
				sb.append((char) bytes[i]);
			}
			temp = sb.toString();
		}
		temp = temp.replaceAll(" ", "").toLowerCase();
		if (temp.contains("=utf8") || temp.contains("=\'utf8") || temp.contains("=\"utf8") || temp.contains("=utf-8") || temp.contains("=\'utf-8") || temp.contains("=\"utf-8")) {
			return "UTF-8";
		} else if (temp.contains("=gb2312") || temp.contains("=\'gb2312") || temp.contains("=\"gb2312")) {
			return "gb2312";
		} else if (temp.contains("=gbk") || temp.contains("=\'gbk") || temp.contains("=\"gbk")) {
			return "gbk";
		} else {
			if (temp.contains("html")) {
				return "UTF-8";
			}
			return null;
		}
	}

	/**
	 * 保存图片到文件
	 */
	public static boolean saveImage(String url, File file) {
		HttpURLConnection conn = null;
		InputStream is = null;
		FileOutputStream os = null;
		try {
			URL uri = new URL(url);
			conn = (HttpURLConnection) uri.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			long contentLength = conn.getContentLengthLong();
			if ((contentLength > 80 * 1024) && (!file.isFile() || file.length() != contentLength)) {
				File parent = file.getParentFile();
				if (parent.isDirectory() || parent.mkdir() || parent.mkdirs()) {// 只要有一个返回真，目录就创建成功。
					is = conn.getInputStream();
					os = new FileOutputStream(file);
					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = is.read(buffer)) != -1) {
						os.write(buffer, 0, len);
					}
				}
			}
			return true;
		} catch (Exception e) {
		} finally {
			try {
				if (is != null)
					is.close();
				if (os != null)
					os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/**
	 * 读取图片的内容
	 */
	public static byte[] readImageBytes(String url) {
		byte[] bytes = null;
		try {
			URL uri = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.connect();
			InputStream is = conn.getInputStream();
			DataInputStream dis = new DataInputStream(is);
			bytes = new byte[new Long(conn.getContentLengthLong()).intValue()];
			dis.readFully(bytes);
			is.close();
			dis.close();
		} catch (Exception e) {
		}
		return bytes;
	}
}
